using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using SapaFinance.DTO;
using SapaFinance.Domain.Model;

namespace SapaFinance.OOMap.Helpers
{
    public class RequestToAccountDetailsConverter : TypeConverter<Request, AccountDetailDTO>
    {
        private readonly IMappingEngine _mappingEngine;

        public RequestToAccountDetailsConverter(IMappingEngine mappingEngine)
        {
            _mappingEngine = mappingEngine;
        }

        protected override AccountDetailDTO ConvertCore(Request source)
        {
            var accounts = source.Payee.Accounts;
            if (accounts.Any())
            {
                var selectListItems = _mappingEngine.Map<IEnumerable<Account>, IEnumerable<SelectListItem>>(accounts).ToList();
                var primaryAccount = source.PayeeAccount ?? source.Payee.GetPrimaryAccount();
                if (primaryAccount != null)
                {
                    selectListItems.Where(x => x.Value.Equals(primaryAccount.UID.ToString())).Single().Selected = true;
                    return new AccountDetailDTO
                    {
                        AccountList = selectListItems,
                        //CurrencyDetail = new CurrencyDetailDTO
                        //{
                        //    BankName = primaryAccount.Bank.Name,
                        //    CurrencyName = primaryAccount.Currency.Name
                        //}
                    };
                }
                return new AccountDetailDTO()
                {
                    AccountList = selectListItems,
                    //CurrencyDetail = new CurrencyDetailDTO()
                    //{
                    //    BankName = accounts.First().Bank.Name,
                    //    CurrencyName = accounts.First().Currency.Name
                    //}

                };
            }
            return new AccountDetailDTO(){};
        }
    }
}